<?php
namespace app\common;
/**
 * PHP实现jwt
 */
class Jwt {

    //头部
    private static $header=array(
        'alg'=>'HS256', //生成signature的算法
        'typ'=>'JWT'    //类型
    );

    //使用HMAC生成信息摘要时所使用的密钥
    private static $key = "1324";



    public static function getToken(array $payload)
    {
        if(is_array($payload))
        {
            $header=urlencode(json_encode(self::$header,true));
            $payload=urlencode(json_encode($payload,true));
            $token=$header.'.'.$payload.'.'.urlencode($header . $payload . self::$key . self::$header['alg']);
            return $token;

            //实际开发时，将token和expireTime放到user表，setTime放到日志表
            /*
                 $user_id = 1;
                $setTime = time();
                $expireTime = time() + 7200;
                $sql1 = "update user  where user_id = $user_id set setTime = $expireTime";
                $sql2 = "insert into log (user_id, set_time) values ($user_id, $setTime)";
            */
        }else{
            return false;
        }
    }


    public static function verifyToken($Token)
    {
        $tokens = explode('.', $Token);
        if (count($tokens) != 3)
            return false;

        list($header, $payload, $sign) = $tokens;

        //获取jwt算法
        if (empty(json_decode(urldecode($header), true)['alg'])){
            return '签名算法不匹配';
        }

        //签名验证
        if (urlencode($header . $payload . self::$key  . self::$header['alg']) !== $sign)
            return '签名错误';

        $payload = json_decode(urldecode($payload), JSON_OBJECT_AS_ARRAY);

        /*实际开发时，验证当前时间是否比user表中的expireTime大*/
        if (isset($payload['expireTime']) && $payload['expireTime'] < time())
            return '签名失效';

        return $payload;
    }


}
